package com.miplus.ccrm.core.service.cust;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.JSysUser;
import com.miplus.ccrm.core.controller.vo.cust.CustScoreSynReqVo;
import com.miplus.ccrm.core.controller.vo.cust.CustSreHistPageReqVo;
import com.miplus.ccrm.core.controller.vo.cust.CustSreHistPageResVo;
import com.miplus.ccrm.core.mapper.FiCustomerScorecardHistMapper;
import com.miplus.ccrm.core.pojo.FiCustomerScorecard;
import com.miplus.ccrm.core.pojo.FiCustomerScorecardHist;
import com.miplus.ccrm.sms.LineAPIR;
import com.miplus.ccrm.sms.OnLineApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Yaohui
 * @description 针对表【fi_customer_scorecard_hist(客户C卡计分表)】的数据库操作Service实现
 * @createDate 2025-06-08 14:08:44
 */
@Slf4j
@Service
public class FiCustomerScorecardHistServiceImpl extends MPJBaseServiceImpl<FiCustomerScorecardHistMapper, FiCustomerScorecardHist>
        implements FiCustomerScorecardHistService{

    @Resource
    OnLineApiService onLineApiService;

    @Resource
    private FiCustomerScorecardService customerScorecardService;

    @Override
    public IPage<CustSreHistPageResVo> customerScorecardHistPage(CustSreHistPageReqVo reqVo) {

        return selectJoinListPage(new Page<>(reqVo.getPageNum(),reqVo.getPageSize()),
                CustSreHistPageResVo.class,
                new MPJLambdaWrapper<>(FiCustomerScorecardHist.class)
                        .selectAll(FiCustomerScorecardHist.class)
                        .selectAs("fun_getnames('CCARD.STATUS',t.status)",CustSreHistPageResVo::getStatusDesc)
                        .eq(ObjectUtils.isNotEmpty(reqVo.getStatus()),FiCustomerScorecardHist::getStatus,reqVo.getStatus())
                        .eq(ObjectUtils.isNotEmpty(reqVo.getRuleStepId()),FiCustomerScorecardHist::getRuleStepId,reqVo.getRuleStepId())
                        .eq(ObjectUtils.isNotEmpty(reqVo.getCustomernumber()),FiCustomerScorecardHist::getCustomernumber,reqVo.getCustomernumber())
                        .eq(ObjectUtils.isNotEmpty(reqVo.getBatchid()),FiCustomerScorecardHist::getBatchid,reqVo.getBatchid())
                        .ge(ObjectUtils.isNotEmpty(reqVo.getApidts()),FiCustomerScorecardHist::getApidt,reqVo.getApidts())
                        .le(ObjectUtils.isNotEmpty(reqVo.getApidte()),FiCustomerScorecardHist::getApidt,reqVo.getApidte())
                        .ge(ObjectUtils.isNotEmpty(reqVo.getRecalldt1()),FiCustomerScorecardHist::getResonDt,reqVo.getRecalldt1())
                        .le(ObjectUtils.isNotEmpty(reqVo.getRecalldt2()),FiCustomerScorecardHist::getResonDt,reqVo.getRecalldt2())
                        .ne(ObjectUtils.isNotEmpty(reqVo.getCustomernumber()),FiCustomerScorecardHist::getCCardScore,-9999.00)
                        .orderByDesc(ObjectUtils.isEmpty(reqVo.getCustomernumber()),FiCustomerScorecardHist::getApidt)
                        .orderByDesc(ObjectUtils.isNotEmpty(reqVo.getCustomernumber()),FiCustomerScorecardHist::getResonDt)
        );
    }

    @Transactional
    @Override
    public CmdResVo synCustScore(JSysUser user,CustScoreSynReqVo reqVo) {
        Date currentDate=new Date();

        try {
            for (Long id : reqVo.getScoreidList()) {
                FiCustomerScorecardHist scorecardHist = baseMapper.selectById(id);
                LineAPIR lineAPIR = onLineApiService.CAFP0002(scorecardHist.getApplyId());
                JSONObject jsonObject = lineAPIR.getJsonObject();
                log.debug("ttJsonObject:{}",jsonObject);
                JSONObject ret = JSONObject.parseObject(jsonObject.get("RetrnMsg").toString());

                if(!"9000".equals(ret.getString("reasonCode"))){//9000才是 评分流程结束的
                    continue;
                };

                String applyId = ret.getString("applyId");
                if(!scorecardHist.getApplyId().equals(applyId)){
                    continue;
                }
                if("true".equals(jsonObject.getString("ScssFlg"))){
                    scorecardHist.setStatus("R");
                }else{
                    scorecardHist.setStatus("F");
                }

                scorecardHist.setReasonCode(ret.getInteger("reasonCode"));
                scorecardHist.setReasonDesc(ret.getString("reasonDesc"));
                scorecardHist.setWorkflowCode(ret.getString("workflowCode"));
                scorecardHist.setWorkflowVersion(ret.getInteger("workflowVersion"));
                scorecardHist.setProductCode(ret.getString("productCode"));
                scorecardHist.setFinalDealTypeCode(ret.getString("finalDealTypeCode"));

                JSONObject envVariable = ret.getJSONObject("envVariable");
                scorecardHist.setRiskCode(envVariable.getString("riskCode"));
                scorecardHist.setRiskCodeDetail(envVariable.getString("riskCodeDetail"));
                scorecardHist.setCCardScore(envVariable.getDouble("cCardScore"));
                scorecardHist.setCustomerLevel(envVariable.getString("customerLevel"));
                scorecardHist.setIsStop(envVariable.getString("isStop"));
                scorecardHist.setIsStopReason(envVariable.getString("isStopReason"));
                scorecardHist.setFeature1(envVariable.getString("feature1"));
                scorecardHist.setFeature2(envVariable.getString("feature2"));
                scorecardHist.setFeature3(envVariable.getString("feature3"));
                scorecardHist.setFeature4(envVariable.getString("feature4"));
                scorecardHist.setFeature5(envVariable.getString("feature5"));
                scorecardHist.setOtherFeature(envVariable.getString("otherFeature"));


                scorecardHist.setMddt(currentDate);
                scorecardHist.setMdusr(user.getUsrid());
                scorecardHist.setReasonText(ret.toString());
                boolean re = updateById(scorecardHist);
                if(re){
                    FiCustomerScorecard customerScorecard=new FiCustomerScorecard();
                    BeanUtils.copyProperties(scorecardHist,customerScorecard);
                    log.info("customerScorecard:{}",customerScorecard);
                    customerScorecardService.updateById(customerScorecard);
                }
            }
            return new CmdResVo(1,"ok");
        } catch (BeansException e) {
            log.error("synCustScore->error:{}",e.getMessage());
            return new CmdResVo(0,"error");
        }

    }



}